import './login.css';
import { useState } from 'react';

import { PhoneIcon, LockIcon, BellIcon } from '@chakra-ui/icons'
import { 
  Button,
  Box,
  Divider,
  AbsoluteCenter,
  Link,
  Image,
  Tabs,
  Tab,
  TabList,
  TabPanels,
  TabPanel,
  Input,
  Checkbox,
  Card,
  CardBody,
  Text,
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  InputGroup,
  InputLeftElement,
  InputRightElement,
  useToast,
  FormErrorMessage,
  FormControl,
} from '@chakra-ui/react'
// import { useFormik } from 'formik';
// import * as Yup from 'yup';
import axios from 'axios'
const baseUrl = 'https://api.realworld.io/api/'
const baseConfig = {
  headers: {
    'Content-Type': 'application/json'
  }
}

// const validationSchema = Yup.object({
//   name: Yup.string().required('请输入姓名'),
//   email: Yup.string().email('请输入有效的电子邮件地址').required('请输入电子邮件地址'),
// });







const commonComponents = (isLogin = true) => {
  const linkList = [
    {
      href: 'https://api.weibo.com/oauth2/authorize?client_id=1881139527&redirect_uri=https%3A%2F%2Fwww.jianshu.com%2Fusers%2Fauth%2Fweibo%2Fcallback&response_type=code&state=%257B%257D###',
      src: 'https://h5.sinaimg.cn/m/weibo-lite/img/pwalogo.417d1674.svg'
    },
    {
      href: 'https://www.jianshu.com/users/auth/wechat',
      src: 'https://bizaladdin-image.baidu.com/0/pic/1300198067_220251832_-1058348626.jpg',
    },
    {
      href: 'https://www.jianshu.com/users/auth/qq_connect',
      src: 'https://qzonestyle.gtimg.cn/qzone/qzact/act/external/tiqq/logo.png',
    },
  ]
  let listListDom = []
  linkList.forEach((item,index) => {
    if(!(!isLogin && index == 0)) listListDom.push(<Link href={item.href} key={item.href}>
      <Image className='img' boxSize='50px' src={item.src} alt='Dan Abramov' />
    </Link>)
    
  })
  return (
    <div className='more-sign'>
      <Box position='relative' padding='10'>
        <Divider />
        <AbsoluteCenter bg='white' px='4'>
          <Text>社交帐号登录</Text>
        </AbsoluteCenter>
      </Box>
      <Box className='link-wrapper'>
        {listListDom}
      </Box>
    </div>
  )
}


function LoginRegister() {
  // formik 对 chakra表单元素 进行表单验证和表单提示
  const toast = useToast();
  const $toast = (title, status = 'error') => {
    toast({
      title,
      status,
      duration: 3000,
      isClosable: true,
    })
  }
  const [telOrPsd, setTelOrPsd] = useState('');
  const [loginPassword, setLoginPassword] = useState('');
  const [nickname, setNickname] = useState('');
  const [tel, setTel] = useState('');
  const [code, setCode] = useState('123456');
  const [showCode, setShowCode] = useState(false);
  const [registerPassword, setRegisterPassword] = useState('');
  const handleChange = (type, event,) => {
    console.log('handleChange',event, type)
    switch(type) {
      case 'telorpsd':  setTelOrPsd(event.target.value);break;
      case 'loginpassword':  setLoginPassword(event.target.value);break;
      case 'nickname':  setNickname(event.target.value);break;
      case 'tel':  
        if(event.target.value.length>0) setShowCode(true)
        setTel(event.target.value);break;
      case 'code':  setCode(event.target.value);break;
      case 'registerpassword':  setRegisterPassword(event.target.value);break;
      
    }
  }
  const handleLogin = () => {
    console.log(telOrPsd, loginPassword)
    // 表单验证
    if(!telOrPsd || !loginPassword) return $toast('手机号码/邮箱地址或密码不能为空')
    axios.post(baseUrl + 'users/login', {
      ...baseConfig,
        "user":{    
          "email": "jak1e@jake.jake",   
          "password": "jakejake"
            }
    }
  )
    .then(function (response) {
      console.log();
      if(response?.data?.user?.token) {
        $toast('登录成功', 'success')
      } else {
        $toast('手机号码/邮箱地址，或密码不正确，请重试')
      }
    })
    .catch(function (error) {
      console.log(error);
    });
  }
  const handleRegister = () => {
    // 表单提示：
    if(!nickname) return $toast('手机号码/邮箱地址或密码不能为空')
    // 请输入昵称
    const pattern = /^[\u4e00-\u9fa5\w]{2,15}$/
    if(!pattern.test(nickname)) return $toast('昵称格式不正确，需要是2-15个字符，只能包含英文中文下划线，不能包含空格。')
    const pattern2 = /^1[3-9]\d{9}$/;
    if(!pattern2.test(tel)) return $toast('请输入正确的手机号')
    const pattern3 = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
    if(registerPassword.length<8) return $toast('密码不能少于8个字符')
    if(!pattern.test(registerPassword)) return $toast('密码需要包含字母和数字')
    // 昵称 
    // 密码不能少于8个字符
    console.log(nickname, tel, registerPassword)
    axios.post(baseUrl + 'users', {
      ...baseConfig, 
      // {
          "user":{   
            "username": "J1acob",
            "email": "jak1e@jake.jake",
            "password": "jakejake"
          }
      // }
    })
    .then(function (res) {
      console.log(res.response, res?.status, res?.response?.data?.errors?.username[0]);
      if(res?.response?.status !== 200) $toast(res?.response?.data?.errors?.username[0] || '注册失败')
    })
    .catch(function (error) {
      console.log(error);
      if(error?.response?.status !== 200) $toast(error?.response?.data?.errors?.username[0] || '注册失败')
    });
  }


  // const formik = useFormik({
  //   initialValues: {
  //     name: '',
  //     email: '',
  //   },
  //   validationSchema,
  //   onSubmit: async (values) => {
  //     await new Promise((resolve) => setTimeout(resolve, 1000));
  //     alert(JSON.stringify(values, null, 2));
  //   },
  // });

  

  return (
    <div className="App">
      {/* 登录注册页面 */}
      {
        
        <Card className='login-card'>
          <CardBody>
            <Tabs>
              <TabList>
                <Tab><Text>登录</Text></Tab>
                <div>·</div>
                <Tab><Text>注册</Text></Tab>
              </TabList>

              <TabPanels>
                <TabPanel>

                {/* <form onSubmit={formik.handleSubmit}>
                  <FormControl isInvalid={formik.touched.name && formik.errors.name}>
                    <Input
                      id="name"
                      name="name"
                      type="text"
                      value={formik.values.name}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                    />
                    <FormErrorMessage>{formik.errors.name}</FormErrorMessage>
                  </FormControl>
                  <FormControl isInvalid={formik.touched.email && formik.errors.email} mt={4}>
                    <Input
                      id="email"
                      name="email"
                      type="email"
                      value={formik.values.email}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                    />
                    <FormErrorMessage>{formik.errors.email}</FormErrorMessage>
                  </FormControl>
                  <Button type="submit" colorScheme="blue" mt={4} isLoading={formik.isSubmitting}>
                    提交
                  </Button>
                </form> */}

                  <InputGroup>
                    <InputLeftElement pointerEvents='none'>
                        <PhoneIcon color='gray.300' />
                    </InputLeftElement>
                    <Input type='tel' placeholder='手机号或邮箱' value={telOrPsd} onChange={handleChange.bind(null, 'telorpsd')} />
                  </InputGroup>
                  <InputGroup>
                    <InputLeftElement pointerEvents='none'>
                        <LockIcon color='gray.300' />
                    </InputLeftElement>
                    <Input type='tel' value={loginPassword} onChange={handleChange.bind(null, 'loginpassword')} placeholder='密码' />
                  </InputGroup>
                  <div className='checkwrapper'>
                    <Checkbox defaultChecked><Text>记住我</Text></Checkbox>
                    <Menu placement="bottom-end">
                        <MenuButton>
                        登录遇到问题?
                        </MenuButton>
                        <MenuList>
                            <MenuItem>用手机号重置密码</MenuItem>
                            <MenuItem>用邮箱重置密码</MenuItem>
                            <MenuItem>无法用海外手机号登录</MenuItem>
                            <MenuItem>无法用 Google 帐号登录</MenuItem>
                        </MenuList>
                    </Menu>
                    {/* <Text>登录遇到问题?</Text> */}
                  </div>
                  <Button colorScheme='blue'  sx={{ width: '100%',background: '#3194d0',margin: '15px 0 30px 0' }} onClick={handleLogin}><Text>登录</Text></Button>
                  {commonComponents()}
                </TabPanel>
                <TabPanel>
                  <InputGroup>
                    <InputLeftElement pointerEvents='none'>
                        <PhoneIcon color='gray.300' />
                    </InputLeftElement>
                    <Input type='tel' value={nickname} onChange={handleChange.bind(null, 'nickname')} placeholder='你的昵称' />
                  </InputGroup>
                  <InputGroup>
                    <InputLeftElement pointerEvents='none'>
                        <PhoneIcon color='gray.300' />
                    </InputLeftElement>
                    <Input type='tel' value={tel} onChange={handleChange.bind(null, 'tel')} placeholder='手机号' />
                  </InputGroup>
                  {
                    showCode && 
                    <InputGroup>
                      <InputLeftElement pointerEvents='none'>
                          <BellIcon color='gray.300' />
                      </InputLeftElement>
                      <Input type='tel' value={code} onChange={handleChange.bind(null, 'code')} placeholder='手机验证码' />
                      <InputRightElement sx={{width: '90px'}}>
                        <Button sx={{fontSize: '16px'}}>发送验证码</Button>
                      </InputRightElement>
                    </InputGroup>
                  }
                  <InputGroup>
                    <InputLeftElement pointerEvents='none'>
                        <LockIcon color='gray.300' />
                    </InputLeftElement>
                    <Input type='tel' value={registerPassword} onChange={handleChange.bind(null, 'registerpassword')} placeholder='设置密码' />
                  </InputGroup>
                  <Button onClick={handleRegister} colorScheme='green' sx={{background: '#42c02e', width: '100%', margin: '15px 0 0px 0'}}>注册</Button>
                  <div className='agreewrapper'>
                  点击 “注册” 即表示您同意并愿意遵守简书<Link sx={{color: '#3194d0'}} to='https://www.jianshu.com/p/c44d171298ce'>用户协议</Link>和<Link sx={{color: '#3194d0'}} to='https://www.jianshu.com/p/2ov8x3'>隐私政策</Link>。
                  </div>
                  {commonComponents(false)}
                </TabPanel>
              </TabPanels>
            </Tabs>
          </CardBody>
        </Card>
      }


    </div>
  );
}

export default LoginRegister;
